/**
 * Author:yuiop
 * Date:2023/2/10 11:49
 */
package com.devops.admin.temporal.activity.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.devops.admin.event.ProjectVersionPhaseChangeEvent;
import com.devops.admin.model.DOSProjectVersion;
import com.devops.admin.service.DOSProjectVersionPhaseRelationService;
import com.devops.admin.service.DOSProjectVersionService;
import com.devops.admin.temporal.activity.DOSProjectVersionTimeoutActivity;
import com.devops.admin.vo.DOSVersionOperationVo;
import com.devops.constant.DevOpsConstant;
import com.devops.constant.ProjectVersionPhaseEnum;
import com.devops.constant.TimeOutOperationEnum;
import io.temporal.spring.boot.ActivityImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
@ActivityImpl(taskQueues = DevOpsConstant.PROJECT_VERSION_WORKFLOW_TASK_QUEUE)
public class DOSProjectVersionTimeoutActivityImpl implements DOSProjectVersionTimeoutActivity {

    @Autowired
    DOSProjectVersionPhaseRelationService dosProjectVersionPhaseRelationService;
    @Autowired
    DOSProjectVersionService dosProjectVersionService;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    @Override
    public Boolean dealProjectVersionTimeout(Integer projectVersionId, TimeOutOperationEnum operationEnum) {
        log.info("**********deal project version timeout start {}", projectVersionId);

        DOSProjectVersion projectVersion = dosProjectVersionPhaseRelationService.getTimeoutProjectVersion(projectVersionId);

        if (ObjectUtil.isNotNull(projectVersion)) {
            if (TimeOutOperationEnum.NOTICE.equals(operationEnum)) {
                applicationEventPublisher.publishEvent(new ProjectVersionPhaseChangeEvent(ProjectVersionPhaseEnum.TIMEOUT, projectVersion, null));
            } else if (TimeOutOperationEnum.CLOSE.equals(operationEnum)) {
                DOSVersionOperationVo vo = new DOSVersionOperationVo();
                BeanUtil.copyProperties(projectVersion, vo);
                vo.setVersionId(projectVersionId);
                vo.setOperationType(DevOpsConstant.ProjectVersionOperateActionType.SYSTEM_FINISH);
                vo.setOperateSourceType(DevOpsConstant.ProjectVersionOperateSourceType.SYSTEM_TYPE);
                dosProjectVersionService.processOperation(vo);
            }
        }

        return ObjectUtil.isNotNull(projectVersion);
    }
}
